package cn.e3mall.sso.service.impl;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.mapper.TbUserMapper;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.pojo.TbUserExample;
import cn.e3mall.sso.service.LoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private JedisClient jedisClient;

    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public E3Result userLogin(String userName, String password) {
        TbUserExample tbUserExample = new TbUserExample();
        tbUserExample.createCriteria().andUsernameEqualTo(userName);
        List<TbUser> tbUsers = tbUserMapper.selectByExample(tbUserExample);
        if(tbUsers.size()==0||tbUsers==null){
            return E3Result.build(400,"用户名或密码错误");
        }
        TbUser tbUser = tbUsers.get(0);
        boolean equals = tbUser.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()));
        if(!equals){
            return E3Result.build(400,"用户名或密码错误");
        }
        tbUser.setPassword(null);
        String token = UUID.randomUUID().toString();
        jedisClient.set("SESSION:"+token,JSONObject.toJSONString(tbUser));
        jedisClient.expire("SESSION:"+token,SESSION_EXPIRE);
        return E3Result.ok(token);
    }
}
